package it.leehook.mp3.activities;

import it.leehook.mp3.R;
import it.leehook.mp3.buttons.ExecuteBtn;
import it.leehook.mp3.utils.Constants;
import it.leehook.mp3.utils.SongUtils;

import java.io.File;
import java.util.ArrayList;

import org.apache.commons.lang.StringUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.bugsense.trace.BugSenseHandler;

/**
 * Activity principale di LeeMP3
 * 
 * @author l.angelini
 * 
 */
public class MainActivity extends Activity {

	public static File musicPath;
	private static File workPath;
	private TextView work;
	private TextView music;
	private SharedPreferences sPrefs;
	public static int counter;
	private String workResult;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		BugSenseHandler.initAndStartSession(MainActivity.this, "8f4dd3a0");
		setContentView(R.layout.main);
		sPrefs = PreferenceManager
				.getDefaultSharedPreferences(getBaseContext());
		String percorsoWork = sPrefs.getString(Constants.WORK_PREFS, "");
		String percorsoMusic = sPrefs.getString(Constants.MUSIC_PREFS, "");
		music = (TextView) findViewById(R.id.musicPath);
		music.setText(getString(R.string.musicFolder) + percorsoMusic);
		work = (TextView) findViewById(R.id.workPath);
		work.setText(getString(R.string.workFolder) + percorsoWork);
		musicPath = new File(percorsoMusic);
		workPath = new File(percorsoWork);
		ExecuteBtn exec = (ExecuteBtn) findViewById(R.id.execute);
		exec.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				try {
					execute(v.getContext());
				} catch (Exception e) {
					Toast.makeText(v.getContext(),
							"Errore : " + e.getMessage(), Toast.LENGTH_LONG)
							.show();
				}
			}
		});
	}

	/**
	 * Crea il menu delle opzioni che appare alla pressione del tasto Menu
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.opt_menu, menu);
		return true;
	}

	/**
	 * Apre il menu
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.prefs:
			startPreferences();
			return true;
		case R.id.exit:
			exit();
			return true;
		default:
			return false;
		}
	}

	/**
	 * Azione richiamata al resume dell'activity
	 */
	@Override
	protected void onResume() {
		super.onResume();
		if (music == null) {
			music = (TextView) findViewById(R.id.musicPath);
		}
		music.setText(getString(R.string.musicFolder)
				+ sPrefs.getString(Constants.MUSIC_PREFS, ""));
		if (work == null) {
			work = (TextView) findViewById(R.id.workPath);
		}
		work = (TextView) findViewById(R.id.workPath);
		work.setText(getString(R.string.workFolder)
				+ sPrefs.getString(Constants.WORK_PREFS, ""));
		musicPath = new File(sPrefs.getString(Constants.MUSIC_PREFS, ""));
		workPath = new File(sPrefs.getString(Constants.WORK_PREFS, ""));
	}

	/**
	 * Mostra le preferenze
	 */
	private void startPreferences() {
		Intent intent = new Intent(this, Preferences.class);
		startActivity(intent);
	}

	/**
	 * Mostra l'activity per l'inserimento dei tag
	 */
	private void startEditTag() {
		Intent intent = new Intent(this, EditTagActivity.class);
		startActivity(intent);
	}

	/**
	 * Procede con l'operazione di lettura/spostamento delle canzoni
	 * 
	 * @param ctx
	 */
	private void execute(Context ctx) {
		counter = 0;
		workResult = "";
		try {
			if (workPath != null) {
				new InitTask().execute(workPath);
			} else {
				workResult = "Inserire il percorso su cui operare!";
			}
		} catch (Exception e) {
			workResult = "Errore : " + e.getMessage();
		}
		toastResult();
	}

	/**
	 * Stampa sul Toast il risultato dell'operazione
	 */
	private void toastResult() {
		if (StringUtils.isNotBlank(workResult)) {
			Toast.makeText(MainActivity.this, workResult, Toast.LENGTH_LONG)
					.show();
		}
	}

	/**
	 * Chiede conferma per l'uscita dall'app
	 */
	private void exit() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(getString(R.string.confirmMsg));
		builder.setCancelable(false);
		builder.setPositiveButton(getString(R.string.yes),
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						BugSenseHandler.closeSession(MainActivity.this);
						MainActivity.this.finish();
					}
				}).setNegativeButton(getString(R.string.no),
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		AlertDialog alert = builder.create();
		alert.show();
	}

	public class InitTask extends AsyncTask<File, Object[], String> {

		private ProgressDialog pd;

		/**
		 * Cicla sui file o sulle directory del path ricevuto ed esegue
		 * l'operazione richiesta
		 * 
		 * @param path
		 * @param operazione
		 * @throws Exception
		 */
		@Override
		protected String doInBackground(File... params) {
			File[] list = params[0].listFiles();
			final int totalSongs = list.length;
			if (totalSongs > 0) {
				MainActivity.this.runOnUiThread(new Runnable() {
					public void run() {
						pd.show();
					}
				});
				for (int i = 0; i < totalSongs; i++) {
					File file = list[i];
					if (file.isFile()) {
						final String filename = file.getName();
						publishProgress(new Object[] { (100 / totalSongs) * i,
								filename });
						try {
							if (StringUtils.endsWithIgnoreCase(file.getName(),
									"mp3")) {
								SongUtils.checkMP3Tags(file);
							} else if (StringUtils.endsWithIgnoreCase(
									file.getName(), "ogg")) {
								SongUtils.checkOGGTags(file);
							} else if (StringUtils.endsWithIgnoreCase(
									file.getName(), "mp4")
									|| (StringUtils.endsWithIgnoreCase(
											file.getName(), "m4a"))) {
								SongUtils.checkM4ATags(file);
							} else if (StringUtils.endsWithIgnoreCase(
									file.getName(), "wav")
									|| StringUtils.endsWithIgnoreCase(
											file.getName(), "wma")) {
								SongUtils.checkWAVTags(file);
							}
							counter++;
						} catch (Exception e) {
							if (StringUtils.equals(e.getMessage(),
									Constants.TAG_MANCANTI)) {
								EditTagActivity.filesToEdit.add(file);
							} else {
								BugSenseHandler.sendEvent("Errore: "
										+ e.getMessage());
								workResult = e.getMessage();
							}
						}
						try {
							Thread.sleep(1000);
						} catch (InterruptedException e) {
							Log.e("AsyncTask", e.getMessage());
						}
					}
				}
				publishProgress(new Object[] { 100, "Finishing..." });
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					Log.e("AsyncTask", e.getMessage());
				}
			} else {
				workResult = "Non ci sono canzoni da spostare";
				return "";
			}
			if (counter > 0) {
				workResult = counter + "/" + totalSongs
						+ " canzoni spostate correttamente!";
			} else {
				if (StringUtils.isBlank(workResult)) {
					workResult = "Nessuna canzone spostata";
				}
			}
			return "";
		}

		@Override
		protected void onPreExecute() {
			pd = new ProgressDialog(MainActivity.this);
			pd.setCancelable(true);
			pd.setMessage("Working ...");
			pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			pd.setProgress(0);
			pd.setMax(100);
			EditTagActivity.filesToEdit = new ArrayList<File>();
		}

		@Override
		protected void onProgressUpdate(Object[]... values) {
			pd.setProgress((Integer) values[0][0]);
			pd.setMessage((String) values[0][1]);
		}

		@Override
		protected void onPostExecute(String result) {
			if (!EditTagActivity.filesToEdit.isEmpty()) {
				startEditTag();
				pd.dismiss();
			} else {
				SongUtils.cleanEmptyDirs(workPath);
				pd.dismiss();
				toastResult();
			}
		}
	}
}